﻿using DTcms.Common;
using DTcms.Model;
using DTcms.Web.Mvc.Areas.Admin.Controllers;
using DTcms.Web.Mvc.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Mvc;

namespace DTcms.Web.Mvc.Controllers
{
    public class Admin_AjaxController : UnitController
    {
        Model.userconfig userConfig = new BLL.userconfig().loadConfig(); //会员配置信息
        Model.manager adminInfo = null;
        
        /// <summary>
        /// Api核心事务
        /// </summary>
        private BaseApi _service = new BaseApi();

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //取得管理员登录信息
            adminInfo = new ManageController().GetAdminInfo();

            //检查管理员是否登录
            if (null == adminInfo)
            {
                filterContext.Result = new JsonResult
                {
                    Data = new { status = 0, msg = "尚未登录或已超时，请登录后操作！" },
                    ContentEncoding = Encoding.UTF8,
                    ContentType = "application/json",
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            base.OnActionExecuting(filterContext);
        }
        #region 获取登录用户权限
        /// <summary>
        /// 获取登录用户权限。
        /// </summary>
        /// <returns></returns>
        public JsonResult GetPermission()
        {
            BLL.manager_role bll = new BLL.manager_role();
            Model.manager_role model = bll.GetModel(adminInfo.role_id);
            return Json(new { role_id = adminInfo.role_id, data = model.manager_role_values, role_type = model.role_type });
        }
        #endregion

        #region 根据URL获取调用别名
        [HttpGet]
        public JsonResult nav_name(string link_url)
        {
            string navNmae = string.Empty;
            if (string.IsNullOrEmpty(link_url))
            {
                return Json(new { status = 0, msg = "必填项不能为空！" });
            }
            else
            {
                if (link_url.IndexOf("/article/") > -1)
                {
                    string cid = Utils.GetQueryString("channel_id", link_url);
                    link_url = Regex.Match(link_url, @".*?(?=[?])").Value.Replace("../", "/admin/");
                    navNmae = new BLL.navigation().GetCount("name", "link_url='" + link_url + "' and channel_id=" + cid);
                }
                else
                {
                    link_url = link_url.Replace("../", "");
                    navNmae = new BLL.navigation().GetNavName(link_url);
                }
                if (string.IsNullOrEmpty(navNmae))
                {
                    return Json(new { status = 0, msg = "为找到对应的调用名！" });
                }
                else
                {
                    return Json(new { status = 1, msg = navNmae });
                }
            }
        }
        #endregion

        #region 验证用户名是否可用OK
        public JsonResult username_validate(string param)
        {
            //如果为Null，退出
            if (string.IsNullOrEmpty(param))
            {
                return Json(new { status = "n", info = "用户名不可为空！" });
            }
            //过滤注册用户名字符
            string[] strArray = userConfig.regkeywords.Split(',');
            foreach (string s in strArray)
            {
                if (s.ToLower() == param.ToLower())
                {
                    return Json(new { status = "n", info = "该用户名不可用！" });
                }
            }
            BLL.users bll = new BLL.users();
            //查询数据库
            if (!bll.Exists(param.Trim()))
            {
                return Json(new { status = "y", info = "该用户名可用！" });
            }
            return Json(new { status = "n", info = "该用户名已被注册！" });
        }
        #endregion

        #region 验证手机号是否可用OK
        public JsonResult mobile_validate(string param)
        {
            //如果为Null，退出
            if (string.IsNullOrEmpty(param))
            {
                return Json(new { status = "n", info = "手机号不可为空！" });
            }
            //过滤注册用户名字符
            string[] strArray = userConfig.regkeywords.Split(',');
            foreach (string s in strArray)
            {
                if (s.ToLower() == param.ToLower())
                {
                    return Json(new { status = "n", info = "该手机号不可用！" });
                }
            }
            BLL.users bll = new BLL.users();
            //查询数据库
            if (!bll.ExistsMobile(param.Trim()))
            {
                return Json(new { status = "y", info = "该手机号可用！" });
            }
            return Json(new { status = "n", info = "该手机号已被注册！" });
        }
        #endregion

        #region 验证扩展字段是否重复
        public JsonResult attribute_field_validate(string param)
        {
            if (string.IsNullOrEmpty(param))
            {
                return Json(new { status = "n", info = "名称不可为空！" });
            }
            BLL.article_attribute_field bll = new BLL.article_attribute_field();
            if (bll.Exists(param))
            {
                return Json(new { status = "n", info = "该名称已被占用，请更换！" });
            }
            return Json(new { status = "y", info = "该名称可使用！" });
        }
        #endregion

        #region 验证频道名称是否是否可用
        public JsonResult channel_name_validate()
        {
            string param = DTRequest.GetString("param");
            string old_channel_name = DTRequest.GetString("old_channel_name");
            if (string.IsNullOrEmpty(param))
            {
                return Json(new { status = "n", info = "频道名称不可为空！" });
            }
            if (param.ToLower() == old_channel_name.ToLower())
            {
                return Json(new { status = "y", info = "该名称可使用！" });
            }
            BLL.site_channel bll = new BLL.site_channel();
            if (bll.Exists(param))
            {
                return Json(new { status = "n", info = "该名称已被占用，请更换！" });
            }
            return Json(new { status = "y", info = "该名称可使用！" });
        }
        #endregion

        #region 验证站点目录名是否可用
        public JsonResult site_path_validate()
        {
            string build_path = DTRequest.GetString("param");
            string old_build_path = DTRequest.GetString("old_build_path");
            if (string.IsNullOrEmpty(build_path))
            {
                return Json(new { status = "n", info = "该目录名不可为空！" });
            }
            if (build_path.ToLower() == old_build_path.ToLower())
            {
                return Json(new { status = "y", info = "该目录名可使用！" });
            }
            BLL.sites bll = new BLL.sites();
            if (bll.Exists(build_path))
            {
                return Json(new { status = "n", info = "该目录名已被占用，请更换！" });
            }
            return Json(new { status = "y", info = "该目录名可使用！" });
        }
        #endregion

        #region 验证URL调用名称是否重复
        public JsonResult urlrewrite_name_validate(string param, string old_name)
        {
            if (string.IsNullOrEmpty(param))
            {
                return Json(new { status = "n", info = "名称不可为空！" });
            }
            if (param.ToLower() == old_name.ToLower())
            {
                return Json(new { status = "y", info = "该名称可使用！" });
            }
            BLL.url_rewrite bll = new BLL.url_rewrite();
            if (bll.Exists(param))
            {
                return Json(new { status = "n", info = "该名称已被使用，请更换！" });
            }
            return Json(new { status = "y", info = "该名称可使用！" });
        }
        #endregion

        #region 验证导航菜单别名是否重复
        public JsonResult navigation_validate()
        {
            string navname = DTRequest.GetString("param");
            string old_name = DTRequest.GetString("old_name");
            if (string.IsNullOrEmpty(navname))
            {
                return Json(new { status = "n", info = "该导航别名不可为空！" });
            }
            if (navname.ToLower() == old_name.ToLower())
            {
                return Json(new { status = "y", info = "该导航别名可使用！" });
            }
            //检查保留的名称开头
            if (navname.ToLower().StartsWith("channel_"))
            {
                return Json(new { status = "n", info = "该导航别名系统保留，请更换！" });
            }
            BLL.navigation bll = new BLL.navigation();
            if (bll.Exists(navname))
            {
                return Json(new { status = "n", info = "该导航别名已被占用，请更换！" });
            }
            return Json(new { status = "y", info = "该导航别名可使用！" });
        }
        #endregion

        #region 验证管理员用户名是否重复
        public JsonResult manager_validate(string param)
        {
            if (string.IsNullOrEmpty(param))
            {
                return Json(new { status = "n", info = "请输入用户名！" });
            }
            BLL.manager bll = new BLL.manager();
            if (bll.Exists(param))
            {
                return Json(new { status = "n", info = "用户名已被占用，请更换！" });
            }
            return Json(new { status = "y", info = "用户名可使用！" });
        }
        #endregion

        #region 验证Tags调用名是否重复
        public JsonResult tags_validate()
        {
            string call_index = DTRequest.GetString("param");
            string old_name = DTRequest.GetString("old_name");
            if (string.IsNullOrEmpty(call_index))
            {
                return Json(new { status = "n", info = "该名称不可为空！" });
            }
            if (call_index.ToLower() == old_name.ToLower())
            {
                return Json(new { status = "y", info = "该名称可以使用！" });
            }
            BLL.article_tags bll = new BLL.article_tags();
            if (bll.Exists(call_index))
            {
                return Json(new { status = "n", info = "该名称已被占用，请更换！" });
            }
            return Json(new { status = "y", info = "该名称可以使用！" });
        }
        #endregion

        #region 获取后台导航字符串
        public JsonResult get_navigation_list()
        {
            Model.manager_role roleModel = new BLL.manager_role().GetModel(adminInfo.role_id); //获得管理角色信息
            if (roleModel == null)
            {
                return Json(new { status = 0, msg = "未获得管理角色信息！" });
            }
            DataTable dt = new BLL.navigation().GetList(0, DTEnums.NavigationEnum.System.ToString());
            get_navigation_childs(dt, 0, roleModel.role_type, roleModel.manager_role_values);

            return Json(new { status = 1, msg = sb.ToString(), pop = listgroup.ToString() });
        }
        public StringBuilder sb = new StringBuilder();
        public StringBuilder listgroup = new StringBuilder();
        public string get_navigation_childs(DataTable oldData, int parent_id, int role_type, List<Model.manager_role_value> ls)
        {
            DataRow[] dr = oldData.Select("parent_id=" + parent_id);
            bool isWrite = false; //是否输出开始标签
            int xt = 0;
            for (int i = 0; i < dr.Length; i++)
            {
                string icon = dr[i]["icon_url"].ToString();
                string link = dr[i]["link_url"].ToString();
                if (!string.IsNullOrEmpty(link) && !link.Contains("/admin"))
                {
                    link = "/admin/" + link.Replace(".aspx", "");
                }
                else
                {
                    link = link.Replace(".aspx", "");
                }
                string title = dr[i]["title"].ToString();
                int class_layer = Utils.ObjToInt(dr[i]["class_layer"]);

                //检查是否显示在界面上
                bool isActionPass = true;
                if (int.Parse(dr[i]["is_lock"].ToString()) == 1)
                {
                    isActionPass = false;
                }
                //检查管理员权限
                if (isActionPass && role_type > 1)
                {
                    string[] actionTypeArr = dr[i]["action_type"].ToString().Split(',');
                    foreach (string action_type_str in actionTypeArr)
                    {
                        //如果存在显示权限资源，则检查是否拥有该权限
                        if (action_type_str == "Show")
                        {
                            Model.manager_role_value modelt = ls.Find(p => p.nav_name == dr[i]["name"].ToString() && p.action_type == "Show");
                            if (modelt == null)
                            {
                                isActionPass = false;
                            }
                        }
                    }
                }
                //如果没有该权限则不显示
                if (!isActionPass)
                {
                    if (isWrite && i == (dr.Length - 1) && parent_id > 0)
                    {
                        listgroup.Append("</ul>");
                        sb.Append("</dl>");
                    }
                    continue;
                }

                //如果是顶级导航
                if (parent_id == 0)
                {
                    xt++;
                    #region 快捷导航
                    listgroup.Append("<div class='list-group'>");
                    listgroup.Append("<h1 title='" + dr[i]["sub_title"].ToString() + "'>");
                    listgroup.Append(icon == "" ? "" : "<i class='" + icon + "'></i>");
                    listgroup.Append("</h1>");
                    listgroup.Append("<div class='list-wrap'>");
                    listgroup.Append("<h2>" + (icon == "" ? "" : "<i class='" + icon + "'></i>") +title + "</h2>");
                    #endregion
                    sb.Append("<ul class='layui-nav layui-nav-tree arrow3 " + (xt == 1 ? "" : "layui-hide") + "' nav-id='xt" + xt + "' lay-filter='admin-side-nav' lay-shrink='all' lay-accordion='true' style='margin: 15px 0;'>");
                    sb.Append("<li class='layui-nav-item list-group'>");
                    sb.Append("<a class='itip'><i class='" + (icon == "" ? "fa fa-leaf" : icon) + "'></i>&emsp;<cite>" + title + "</cite></a>");

                    //调用自身迭代
                    get_navigation_childs(oldData, int.Parse(dr[i]["id"].ToString()), role_type, ls);
                    #region 快捷导航
                    listgroup.Append("</div>");
                    listgroup.Append("</div>");
                    #endregion
                    sb.Append("</li>");
                    sb.Append("</ul>");
                }
                else //下级导航
                {
                    if (!isWrite)
                    {
                        isWrite = true;
                        listgroup.Append("<ul>");
                        sb.Append("<dl class='layui-nav-child'>");
                    }
                    #region 快捷导航
                    listgroup.Append("<li>");
                    listgroup.Append("<a ");
                    #endregion
                    if (class_layer >= 3)
                    {
                        sb.Append("<dd>");
                    }
                    else
                    {
                        sb.Append("<li class='layui-nav-item'>");
                    }
                    sb.Append("<a ");
                    if (!string.IsNullOrEmpty(link))
                    {
                        if (int.Parse(dr[i]["channel_id"].ToString()) > 0)
                        {
                            listgroup.Append(" ew-href='" + link + "?channel_id=" + dr[i]["channel_id"].ToString() + "'");
                            sb.Append(" lay-href='" + link + "?channel_id=" + dr[i]["channel_id"].ToString() + "'");
                        }
                        else
                        {
                            listgroup.Append(" ew-href='" + link + "'");
                            sb.Append(" lay-href='" + link + "'");
                        }
                    }
                    listgroup.Append(" ><span>");
                    listgroup.Append(icon == "" ? "" : "<i class='" + icon + "'></i>");
                    listgroup.Append(title + "</span></a>");

                    sb.Append("><i class='" + (icon == "" ? "fa fa-leaf" : icon) + "'></i>&emsp;<cite>" + title + "</cite></a>");
                    //调用自身迭代
                    get_navigation_childs(oldData, int.Parse(dr[i]["id"].ToString()), role_type, ls);
                    listgroup.Append("</li>");

                    if (class_layer >= 3)
                    {
                        sb.Append("</dd>");
                    }
                    else
                    {
                        sb.Append("</li>");
                    }
                    if (i == (dr.Length - 1))
                    {
                        listgroup.Append("</ul>");
                        sb.Append("</dl>");
                    }
                }
            }
            return sb.ToString();
        }
        #endregion

        #region 获取远程文件的信息
        [HttpPost]
        public JsonResult get_remote_fileinfo()
        {
            string filePath = DTRequest.GetFormString("remotepath");
            if (string.IsNullOrEmpty(filePath))
            {
                return Json(new { status = 0, msg = "没有找到远程附件地址！" });
            }
            if (!filePath.ToLower().StartsWith("http://"))
            {
                return Json(new { status = 0, msg = "不是远程附件地址！" });
            }
            try
            {
                HttpWebRequest _request = (HttpWebRequest)WebRequest.Create(filePath);
                HttpWebResponse _response = (HttpWebResponse)_request.GetResponse();
                int fileSize = (int)_response.ContentLength;
                string fileName = filePath.Substring(filePath.LastIndexOf("/") + 1);
                string fileExt = filePath.Substring(filePath.LastIndexOf(".") + 1).ToUpper();
                return Json(new { status = 1, msg = "获取远程文件成功！", name = fileName, path = filePath, size = fileSize, ext = fileExt });
            }
            catch
            {
                return Json(new { status = 0, msg = "远程文件不存在！" });
            }
        }
        #endregion

        #region 发送手机短信
        [HttpPost]
        public JsonResult sms_message_post()
        {
            string mobiles = DTRequest.GetFormString("mobiles");
            string content = DTRequest.GetFormString("content");
            if (mobiles == "")
            {
                return Json(new { status = 0, msg = "手机号码不能为空！" });
            }
            if (content == "")
            {
                return Json(new { status = 0, msg = "短信内容不能为空！" });
            }
            //开始发送
            string msg = string.Empty;
            bool result = new BLL.sms_message().Send(mobiles, content, 2, out msg);
            if (result)
            {
                return Json(new { status = 1, msg = msg });
            }
            return Json(new { status = 0, msg = msg });
        }
        #endregion
        
        #region 获取要生成静态的地址
        public JsonResult get_builder_urls()
        {
            //int state = get_builder_status();
            int state = 1;//默认生成静态 
            if (state == 1)
                return Json(new HtmlBuilder().getpublishsite());
            else
                return Json(state);
        }
        #endregion

        #region 生成静态页面
        public JsonResult get_builder_html()
        {
            //int state = get_builder_status();
            int state = 1;//默认生成静态 
            if (state == 1)
                return Json(new HtmlBuilder().handleHtml());
            else
                return Json(state);
        }
        #endregion

        #region 判断是否登陆以及是否开启静态
        private int get_builder_status()
        {
            if (adminInfo == null)
                return -1;
            else if (!new BLL.manager_role().Exists(adminInfo.role_id, "sys_builder_html", DTEnums.ActionEnum.Build.ToString()))
                return -2;
            else if (siteConfig.staticstatus != 2)
                return -3;
            else
                return 1;
        }
        #endregion

        #region 获取分类列表
        /// <summary>
        /// 获取分类列表
        /// </summary>
        /// <param name="context"></param>
        public JsonResult get_category_list()
        {
            int chanel_id = DTRequest.GetQueryInt("channel_id");
            if (chanel_id == 0)
            {
                return Json(new { status = "n", info = "频道不存在！" });
            }
            else
            {
                BLL.article_category bll = new BLL.article_category();
                DataTable dt = bll.GetList(0, chanel_id);
                if (dt.Rows.Count == 0)
                {
                    return Json(new { status = "n", info = "该频道还未创建分类！" });
                }
                else
                {
                    DataTable table = new DataTable();
                    table.Columns.Add("id", Type.GetType("System.Int32"));
                    table.Columns.Add("title", Type.GetType("System.String"));
                    table.Columns.Add("layer", Type.GetType("System.Int32"));
                    foreach (DataRow adr in dt.Rows)
                    {
                        DataRow dr = table.NewRow();
                        dr["id"] = adr["id"];
                        dr["title"] = adr["title"];
                        dr["layer"] = adr["class_layer"];
                        table.Rows.Add(dr);
                    }
                    return Json(new { status = "y", list = table });
                }
            }
        }
        #endregion

        #region 获取内容列表
        /// <summary>
        /// 获取内容列表
        /// </summary>
        /// <param name="context"></param>
        public JsonResult get_content_list()
        {
            int totalCount = 0;
            int indexPage = DTRequest.GetQueryIntValue("page", 1);
            int pageSize = DTRequest.GetQueryIntValue("size", 10);
            int category_id = DTRequest.GetQueryInt("category_id");
            int chanel_id = DTRequest.GetQueryInt("channel_id");
            string keyword = DTRequest.GetQueryString("keyword").Replace("'", string.Empty);
            if (chanel_id == 0)
            {
                return Json(new { status = "n", msg = "频道不存在！" });
            }
            else
            {
                string strWhere = "status=0";

                BLL.article bll = new BLL.article();
                if (keyword != "")
                {
                    strWhere += string.Format(" and title like '%{0}%'", keyword);
                }
                DataSet ds = bll.GetList(chanel_id, category_id, pageSize, indexPage, strWhere, "sort_id asc,id desc", out totalCount);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    DataTable table = new DataTable();
                    table.Columns.Add("id", Type.GetType("System.Int32"));
                    table.Columns.Add("title", Type.GetType("System.String"));
                    table.Columns.Add("category", Type.GetType("System.String"));

                    BLL.article_category catBll = new BLL.article_category();

                    foreach (DataRow adr in ds.Tables[0].Rows)
                    {
                        DataRow dr = table.NewRow();
                        dr["id"] = adr["id"];
                        dr["title"] = adr["title"];
                        dr["category"] = catBll.GetTitle(Utils.ObjToInt(adr["category_id"]));
                        table.Rows.Add(dr);
                    }
                    return Json(new
                    {
                        list = table,
                        status = "y",
                        page = indexPage,
                        size = pageSize,
                        total = totalCount
                    });
                }
                else
                {
                    return Json(new { status = "n", msg = "未查询到内容！" });
                }
            }
        }
        #endregion
        
        #region 获取文件目录json
        public JsonResult files(string dir)
        {
            //防跨目录
            if (!string.IsNullOrEmpty(dir) && dir != "")
            {
                dir = dir.Replace("..", "") + "/";
            }
            DataTable dt = new DataTable();
            dt.Columns.Add("type", Type.GetType("System.String"));
            dt.Columns.Add("url", Type.GetType("System.String"));
            dt.Columns.Add("name", Type.GetType("System.String"));
            dt.Columns.Add("creationtime", Type.GetType("System.String"));
            dt.Columns.Add("updateTime", Type.GetType("System.String"));
            dt.Columns.Add("size", Type.GetType("System.String"));
            dt.Columns.Add("isDir", Type.GetType("System.Boolean"));

            dt.Columns.Add("smUrl", Type.GetType("System.String"));
            dt.Columns.Add("hasSm", Type.GetType("System.Boolean"));
            string fileurl = string.Format("/{0}/", siteConfig.filepath);
            DirectoryInfo dirInfo = new DirectoryInfo(Utils.GetMapPath(@"" + fileurl + "/" + dir));
            //获取目录
            foreach (DirectoryInfo item in dirInfo.GetDirectories())
            {
                DataRow dr = dt.NewRow();
                dr["type"] = "dir";
                dr["name"] = item.Name;
                dr["isDir"] = "true";
                dr["creationtime"] = item.CreationTime;
                dr["updateTime"] = item.LastWriteTime;
                dt.Rows.Add(dr);
            }
            //获取所有文件
            foreach (FileInfo file in dirInfo.GetFiles())
            {
                string fileExt = Path.GetExtension(file.Extension).Trim('.');
                bool is_img = Utils.IsImage(fileExt);
                DataRow dr = dt.NewRow();
                dr["type"] = is_img ? "file" : fileExt;
                if (is_img)
                {
                    dr["hasSm"] = "true";
                    dr["smUrl"] = string.Format("/{0}{1}{2}", siteConfig.filepath, dir, file.Name);
                }
                dr["name"] = file.Name;
                dr["creationtime"] = file.CreationTime;
                dr["size"] = Utils.CountSize(file.Length);
                dr["updateTime"] = file.LastWriteTime;
                dr["url"] = string.Format("/{0}{1}{2}", siteConfig.filepath, dir, file.Name);
                dr["isDir"] = "false";
                dt.Rows.Add(dr);
            }
            return Json(new { msg = "查询成功", code = 200, data = dt });
        }
        #endregion

        #region 返回操作是否成功
        /// <summary>
        /// 操作成功
        /// </summary>
        /// <returns></returns>
        public void IsYes(string msg)
        {
            Response.Write(JsonHelper.ObjectToJSON(new { status = 1, msg = msg }));
        }
        /// <summary>
        /// 操作失败
        /// </summary>
        /// <returns></returns>
        public void IsNo(string msg)
        {
            Response.Write(JsonHelper.ObjectToJSON(new { status = 0, msg = msg }));
        }
        #endregion

        #region Add

        #endregion
    }
}